package com.seig.teashopping.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seig.teashopping.common.Constants;
import com.seig.teashopping.controller.Dto.UserDto;
import com.seig.teashopping.entity.User;
import com.seig.teashopping.exception.ServiceException;
import com.seig.teashopping.mapper.UserMapper;
import com.seig.teashopping.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张东旭
 * @since 2023-06-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private  UserMapper userMapper;
    public UserDto login(UserDto userDto) {
        User one = getUser(userDto);
        if(one!=null){
            BeanUtils.copyProperties(one,userDto);
            //设置token
//            String token = TokenUtils.getToken(one.getId().toString(), one.getPassword());
//            userDto.setToken(token);
            return userDto;
        } else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }
    public User getUser(UserDto userDto) {
        System.out.println("12312312312");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDto.getUsername());
        queryWrapper.eq("password", userDto.getPassword());
        User one;

//        try {
            one = userMapper.selectOne(queryWrapper);
            return one;
//        } catch (Exception e) {
//            throw new ServiceException(Constants.CODE_500, "系统错误");
//        }
    }



    public User register(UserDto userDto) {
        User one = getUser(userDto);
        if (one==null){
            one = new User();
            BeanUtils.copyProperties(userDto,one);
            userMapper.insert(one);
        }else{
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;
    }

}
